use serde_json::{Value, json};
// 转换菜单为树形结构
pub fn get_menu( data:&mut Vec<Value> ) -> Vec<Value>{
    let list: &mut Vec<Value> = &mut vec![];
    
    if data.is_empty(){
        return list.to_vec();
    }
    
    // 一级菜单
    for v in data.iter_mut() {
        if v["parent"].is_null() || v["parent"].eq(&0) {
            list.push( v.to_owned() );
            v.take();
        }
    }
    data.retain(|v| !v.is_null());

    fn deep(list:&mut Vec<Value>, data:&mut Vec<Value>){
        if !data.is_empty() {
            for p in list.iter_mut(){
                let mut children: Vec<Value> = vec![];
                let id = p["id"].as_i64().unwrap_or_default();
                for v in data.iter_mut(){
                    if !v.is_null() {
                        let parent = v["parent"].as_i64().unwrap_or_default();
                        if id.eq(&parent) {
                            children.push( v.clone() );
                            v.take();
                        }
                    }
                }
                if !children.is_empty() {
                    p["children"] = json!(children)
                }
                
                if !&p["children"].is_null() {
                    let d = p["children"].as_array_mut().unwrap();
                    data.retain(|v| !v.is_null());
                    deep(d, data)
                }
            }
        }
    }
    deep(list, data);
    list.to_vec()
}
// 判断是否存在子菜单
pub fn exists_children(menu:Vec<Value>, id:i32) -> bool {
    let mut arr:Vec<i64> = Vec::new();
    let id = id as i64;
    for v in menu {
        if v["parent"].as_i64().unwrap_or_default().eq(&id)  {
            arr.push(v["id"].as_i64().unwrap())
        }
    }
    arr.is_empty()
}
pub fn get_perm_menu(data:&mut Vec<Value>, perm:Vec<String> ) -> Vec<Value>{
    fn deep(data: &mut Vec<Value>, perm:Vec<String>) -> Vec<Value> {
        for p in data.into_iter() {
            if p["children"].is_null() {
                let id = p["id"].as_i64().unwrap_or_default();
                let mut perm_: Vec<String> = Vec::new();
                for u in perm.to_owned() {
                    let s = u.split("_").collect::<Vec<&str>>();
                    let n = s[0].parse::<i64>().unwrap_or_default();
                    if id == n {
                        if !perm_.contains(&s[1].to_owned()) {
                            perm_.push(s[1].to_owned());
                        }
                    }
                }
                p["perm"] = json!(perm_);
            }else{
                let d = p["children"].as_array_mut().unwrap();
                deep(d, perm.to_owned());
            }
        }
        return data.to_vec()
    }
    deep(data, perm)
}